﻿using ConfExpert.Utility;
using ConfOrder.Properties;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using Extensions;
using SpreadsheetGear;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfOrder.Shirt
{
    public partial class SoldQuantities : XForm
    {
        public SoldQuantities()
        {
            InitializeComponent();
        }

        int OrderRefId = 0;
        int WhoAmI = AppSession.UserInfo.UserId;
        string OrderRef;
        private void SoldItems_Load(object sender, EventArgs e)
        {
            this.MainToolbar.Visible = true;
            btnImport.ItemClick += btnImport_ItemClick;
            btnRefresh.ItemClick += btnRefresh_ItemClick;
            btnSave.ItemClick += btnSave_ItemClick;
            btnDelete.ItemClick += btnDelete_ItemClick;
            btnSendFabricOrder.ItemClick += btnSendFabricOrder_ItemClick;

            //DagilimId = dx.Rows[0]["DagilimId"].ToIntZero();
            btnImport.Enabled = false;
            gleBreakdown.EditValueChanged += gleBreakdown_EditValueChanged;
            gleBreakdown.Edit.Assign(RepositoryManager.riDagilim);

            DataTable dx = AppSession.DataManager.ExecuteDataTable("COGetUserOrderRef", WhoAmI);
            if (dx.Rows.Count > 0)
            {
                OrderRefId = dx.Rows[0]["OrderRefId"].ToIntZero();
                gleBreakdown.EditValue = dx.Rows[0]["DagilimId"].ToIntZero();
                Getir(OrderRefId);
            }
            btnOrderRef.ItemClick += btnOrderRef_ItemClick;
            btnRezerve.ItemClick += btnAutoRoll_ItemClick;

            btnRezerve.Enabled = false;
            btnSendFabricOrder.Enabled = false;
            xtraTabControl1.SelectedPageChanged += xtraTabControl1_SelectedPageChanged;
            gvOrder.RowCellClick += gvOrder_RowCellClick;

            xtraTabControl1.Images = imageList1;
            xtraTabControl1.HeaderButtons = ((DevExpress.XtraTab.TabButtons)(((DevExpress.XtraTab.TabButtons.Prev | DevExpress.XtraTab.TabButtons.Next)| DevExpress.XtraTab.TabButtons.Default)));
            xtraTabControl1.HeaderButtonsShowMode = DevExpress.XtraTab.TabButtonShowMode.Always;
            tpOrder.ImageIndex = 3;
            tpFabrics.ImageIndex = 5;
            tpAccessories.ImageIndex = 6;
        }

        void btnSendFabricOrder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvFabrics.EndEdit();

            DataTable dt = gvFabrics.DataTable();
            int Total = dt.Compute("SUM(MissingQty)", "MissingQty>0.1").ToIntNN();
            if (Total > 0)
                using(SendFabricOrder fo = new SendFabricOrder(dt))
                if (fo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AppSession.DataManager.ExecuteNonQuery("COInsFabricOrderToMustafa", fo.xml, OrderRefId, WhoAmI);
                    gvFabrics.VeriyiGuncelle("COGetQtySoldQuantities2", WhoAmI, OrderRefId, 0);
                    gvFabrics.BestFitColumns();
                }
        }

        void gvOrder_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            GridView gv = sender as GridView;
            switch (gv.FocusedColumn.FieldName)
            {
                case "S1": Goster(gv.GetFocusedRowCellValue("Product1Id").ToIntZero()); break;
                case "S2": Goster(gv.GetFocusedRowCellValue("Product2Id").ToIntZero()); break;
                case "S3": Goster(gv.GetFocusedRowCellValue("Product3Id").ToIntZero()); break;
                case "S4": Goster(gv.GetFocusedRowCellValue("Product4Id").ToIntZero()); break;
            }
        }

        void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            btnSave.Enabled = xtraTabControl1.SelectedTabPage == tpOrder;

            btnRezerve.Enabled =
            btnSendFabricOrder.Enabled = (xtraTabControl1.SelectedTabPage == tpFabrics);
        }

        void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (OrderRefId > 0)
                if (XtraMessageBox.Show("Are you sure to delete the data which belongs to this orderref?", "Confirm", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    ExecQuery("CODelSoldQuantities", OrderRefId);
                    Getir(OrderRefId);
                }
        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvOrder.EndEdit();
            gvOrder.Update("COModelId,COStyleId,ProductId,Product1Id,Product2Id,Product3Id,Product4Id", "COModel");
            Notify("Saved.");
        }

        void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Getir(OrderRefId);
        }


        int DagilimId = 0;
        private void DagilimChanged()
        {
            try
            {
                gvOrder.CloseEditor();
                gvOrder.BeginUpdate();
                if (DagilimId != gleBreakdown.EditValue.ToIntZero())
                {
                    DagilimId = gleBreakdown.EditValue.ToIntZero();

                    ConfOrderDS.AppDS.DagilimRow r = RepositoryManager.dsi.Dagilim.FindByDagilimId(DagilimId);
                    if (r != null)
                        for (int i = 1; i < 16; i++)
                        {
                            string fieldName = String.Format("A{0:00}", i);
                            string cap = r[String.Format("A{0:00}", i)].ToString();
                            gvOrder.Columns[fieldName].ToolTip = cap != string.Empty ? cap : " ";
                        }
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                gvOrder.EndUpdate();
            }
        }

        private void gleBreakdown_EditValueChanged(object sender, EventArgs e)
        {
            int dagilimId = gleBreakdown.EditValue.ToIntZero();
            btnImport.Enabled = dagilimId > 0;
        }

        private void Getir(int OrderRefId)
        {
            if (OrderRefId > 0)
            {
                this.Cursor = Cursors.WaitCursor;
                DataSet d = AppSession.DataManager.ExecuteDataSet("COGetQtySoldQuantities2", WhoAmI, OrderRefId, 1);
                gvOrder.Init(d.Tables[0].Copy());
                gvFabrics.Init(d.Tables[1].Copy());
                gvAksesuar.Init(d.Tables[2].Copy());

                tpFabrics.Text = "Fabrics." + d.Tables[1].Rows.Count.ToString();
                tpAccessories.Text = "Accessories." + d.Tables[2].Rows.Count.ToString();
                //
                AddScan(gvOrder, "S1", "S2", "S3", "S4");
                gvOrder.SetCaptions("Scan:Sc0", "S1:Sc1", "S2:Sc2", "S3:Sc3", "S4:Sc4", "Total:Total Pcs");
                gvOrder.YanYanaGetirCoklu("Cons4",
                    "S1", "Product1Id", "Cons1",
                    "S2", "Product2Id", "Cons2",
                    "S3", "Product3Id", "Cons3",
                    "S4", "Product4Id");

                gvOrder.CustomUnboundColumnData -= gridView1_CustomUnboundColumnData;
                gvOrder.CalcRowHeight -= gridview_CalcRowHeight;

                gvOrder.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
                gvOrder.CalcRowHeight += gridview_CalcRowHeight;

                //
                //gvFabrics.SutunEkle("MissingQty", typeof(decimal), "ProjectedQty-ISNULL(AllocatedQty,0)");
                gvFabrics.YanYanaGetirCoklu("OtherQty", "RequiredQty", "ProjectedQty", "WaitingForRsv", "ReservedQty", "WaitingForOrd", "OrderedQty", "MissingQty", "IdleQty");
                gvFabrics.SetCaptions("WaitingForRsv:Reserved Qty (pending)", "WaitingForOrd:Ordered Qty (pending)");

                gvOrder.MakeColumnInvisible("COSoldQuantitiesId", "OrderRefId", "COOrderId", "COModelId", "DagilimId", "Tarih", "InsertedOn");
                //gvPos.MakeColumnInvisible("MainFabric", "Trim1", "Trim2", "Trim3", "Trim4", "InsertedOn", "COModelId", "COOrderId", "OrderRefId");
                gvOrder.Columns["COStyleId"].ColumnEdit = RepositoryManager.riStyle;
                gvOrder.SetCaptions("ProductId:MainFabric", "Product1Id:Trim1", "Product2Id:Trim2", "Product3Id:Trim3", "Product4Id:Trim4");
                //gvOrder.SetCaptions("ProductId:MainFabric", "Product1Id:Trim1", "Product2Id:Trim2", "Product3Id:Trim3", "Product4Id:Trim4");
                gvAksesuar.SetCaptions("Boy:Size", "Renk:Color", "Aciklama:Expl", "Etiket:Label", "SeriId:Series Id");

                gvOrder.FormatAsNumber(0, "Total");
                //gvOrder.FormatAsNumber(3, "Cons0", "Cons1", "Cons2", "Cons3", "Cons4");
                gvOrder.AddSummary("Total");

                gvFabrics.FormatAsNumber(1, "OtherQty", "RequiredQty", "ProjectedQty", "WaitingForRsv", "ReservedQty", "WaitingForOrd", "OrderedQty", "MissingQty", "IdleQty");
                gvFabrics.AddSummary("OtherQty", "RequiredQty", "ProjectedQty", "WaitingForRsv", "ReservedQty", "WaitingForOrd", "OrderedQty", "MissingQty", "IdleQty");

                gvAksesuar.FormatAsNumber(0, "ProjectedQty", "AllocatedQty", "MissingQty", "IdleQty", "QtyOrdered");
                gvAksesuar.AddSummary("ProjectedQty", "AllocatedQty", "MissingQty", "IdleQty", "QtyOrdered");

                gvOrder.FormatAsNumber(0, "Total");
                gvOrder.FormatAsNumber(3, "Cons0", "Cons1", "Cons2", "Cons3", "Cons4");
                gvOrder.AddSummary("Total");

                gvOrder.BestFitColumns();
                gvFabrics.BestFitColumns();
                gvAksesuar.BestFitColumns();

                gvOrder.MakeReadOnly("COStyleId", "ProductId", "Product1Id", "Product2Id", "Product3Id", "Product4Id");
                gvFabrics.MakeReadOnly();
                gvAksesuar.MakeReadOnly();

                for (int i = 15; i > 1; i--)
                {
                    string col = string.Format("A{0:00}", i);
                    if (gvOrder.DataTable().Select(col + ">0").Length > 0)
                        break;
                    else
                        gvOrder.Columns[col].Visible = false;
                }

                for (int i = 1; i < 15; i++)
                {
                    string col = string.Format("A{0:00}", i);
                    if (gvOrder.DataTable().Select(col + ">0").Length > 0)
                        break;
                    else
                        gvOrder.Columns[col].Visible = false;
                }

                gvOrder.RowStyle -= gvOrder_RowStyle;
                gvOrder.RowCellStyle -= gvAksesuar_RowCellStyle;
                gvAksesuar.RowCellStyle -= gvAksesuar_RowCellStyle;
                gvFabrics.RowCellStyle -= gvAksesuar_RowCellStyle;

                gvOrder.RowStyle += gvOrder_RowStyle;
                gvOrder.RowCellStyle += gvAksesuar_RowCellStyle;
                gvAksesuar.RowCellStyle += gvAksesuar_RowCellStyle;
                gvFabrics.RowCellStyle += gvAksesuar_RowCellStyle;

                DataRow or = RepositoryManager.dsi.COOrderRef.FindByOrderRefId(OrderRefId);
                if (or != null)
                    OrderRef = or["OrderRef"].ToString();
                else
                    OrderRef = string.Empty;
                btnOrderRef.EditValue = OrderRef;

                //DagilimChanged();
                gvOrder.FocusedRowChanged -= gvOrder_FocusedRowChanged;
                gvOrder.FocusedRowChanged += gvOrder_FocusedRowChanged;

                DataTable dx = AppSession.DataManager.ExecuteDataTable("COGetUserOrderRef", WhoAmI);
                if (dx.Rows.Count > 0)
                    gleBreakdown.EditValue = dx.Rows[0]["DagilimId"].ToIntZero();

                DagilimChanged();
                this.Cursor = Cursors.Default;

            }
        }

        void gvAksesuar_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView gv = sender as GridView;
            if (e.RowHandle > -1)
            {
                switch (e.Column.FieldName)
                {
                    case "ProjectedQty":
                    case "MissingQty":
                    case "Total":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        return;
                }
            }
        }

        void gvOrder_RowStyle(object sender, RowStyleEventArgs e)
        {
            DataRow r = ((GridView)sender).GetDataRow(e.RowHandle);
            if (r != null)
                if (r["Total"].ToIntZero() > 0 && (
                    r["ProductId"].ToIntZero() > 0 && r["Cons0"].ToDecimalNN() <= 0 ||
                    r["Product1Id"].ToIntZero() > 0 && r["Cons1"].ToDecimalNN() <= 0 ||
                    r["Product2Id"].ToIntZero() > 0 && r["Cons2"].ToDecimalNN() <= 0 ||
                    r["Product3Id"].ToIntZero() > 0 && r["Cons3"].ToDecimalNN() <= 0 ||
                    r["Product4Id"].ToIntZero() > 0 && r["Cons4"].ToDecimalNN() <= 0))
                    e.Appearance.ForeColor = System.Drawing.Color.SlateGray;
        }

        public void gridview_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.RowHeight < notready.Height)
                    e.RowHeight = notready.Height;
        }

        public void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.ListSourceRowIndex > -1 &&
                e.Column.FieldName.StartsWith("S") && e.Column.FieldName.Length == 2)
                if (e.IsGetData)
                {
                    string col = e.Column.FieldName.Replace("S", "Product") + "Id";

                    if (((DataRowView)e.Row)[col].ToIntZero() > 0)
                    {
                        DataRow[] dr = RepositoryManager.dsi.V_Kumas.Select("ProductId=" + ((DataRowView)e.Row)[col].ToString());
                        if (dr.Length > 0)
                            if (dr[0]["PhotoMikro"] != DBNull.Value)
                                e.Value = dr[0]["PhotoMikro"];
                    }
                }
        }

        void AddScan(GridView gridview, params string[] FieldNames)
        {
            foreach (string FieldName in FieldNames)
            {
                GridColumn colPhoto = new GridColumn();
                colPhoto.FieldName = FieldName;
                gridview.Columns.Add(colPhoto);

                colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";
            }
        }

        void gvOrder_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //DagilimChanged();
        }

        void btnAutoRoll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //AppSession.MainForm.ShowMdiChildForm(typeof(AutoRollSelection), OrderRefId);
            using (Reserve x = new Reserve(OrderRefId))
                x.ShowDialog();

            //if (x.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            gvFabrics.VeriyiGuncelle("COGetQtySoldQuantities2", WhoAmI, OrderRefId, 0);
        }

        void btnOrderRef_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (OrderRef odr = new OrderRef(OrderRefId))
                if (odr.ShowDialog() == DialogResult.OK)
                {
                    OrderRefId = odr.OrderRefId;
                    Getir(OrderRefId);
                }
        }

        void btnImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string xml = ReadFile();

            DataSet d = AppSession.DataManager.ExecuteDataSet("COInsSoldQuantities", gleBreakdown.EditValue.ToIntZero(), xml, OrderRefId);
            Getir(OrderRefId);
        }

        private string ReadFile()
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "Excel Files|*.xls;*.xlsx";
                DialogResult dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileInfo fi = new FileInfo(ofd.FileName);

                    IWorkbook Workbook = SpreadsheetGear.Factory.GetWorkbook(fi.FullName);
                    DataSet ds = Workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.None);   // | SpreadsheetGear.Data.GetDataFlags.NoColumnTypes);
                    return ds.Tables[0].Serialize();
                }
            }
            return string.Empty;
        }
    }
}
